package logic

import (
	"context"
	"errors"
	"fmt"
	"houses/models/cache"
	"houses/models/mysql"

	"houses/houserpc/houserpc"
	"houses/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *houserpc.RegisterRequest) (*houserpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, errors.New("用户已经注册")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SentSms {
		return nil, errors.New("短信验证码错误")
	}

	houses := mysql.User{
		Account:  in.Account,
		Password: in.Password,
		Name:     fmt.Sprintf("用户:%d", 1000),
		Image:    "https://ts3.tc.mm.bing.net/th/id/OIP-C.rPQTtL06uTRQSkiUvIGykwAAAA?cb=thfvnextucfimg=1&rs=1&pid=ImgDetMain&o=7&rm=3",
	}
	mysql.DB.Create(houses)

	return &houserpc.RegisterResponse{
		User: int64(user.ID),
	}, nil
}
